package com.example.administrator.liveapp.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.administrator.liveapp.ApplicationUtils;
import com.example.administrator.liveapp.R;
import com.example.administrator.liveapp.Xutils3.MyCallBack;
import com.example.administrator.liveapp.Xutils3.XUtils;
import com.example.administrator.liveapp.adapter.ArticleRecyclerView1Adapter;
import com.example.administrator.liveapp.adapter.ArticleRecyclerView2Adapter;
import com.example.administrator.liveapp.adapter.ArticleRecyclerView3Adapter;
import com.example.administrator.liveapp.bean.ArticleListBean;
import com.example.administrator.liveapp.utils.AppUrl;
import com.example.administrator.liveapp.utils.GlideImageLoader;
import com.example.administrator.liveapp.view.FullyLinearLayoutManager;
import com.github.nuptboyzhb.lib.SuperSwipeRefreshLayout;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import org.xutils.common.util.LogUtil;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * 文章列表activity
 */

public class ArticlePage extends Activity {

    private String[] cateid;//区分轮播图跳转页面
    private String[] id;//轮播图对应的跳转页面id
    private List<String> images;
    private List<String> titles;
    private Banner banner;
    private ImageView article_title_bar_returns,article_title_bar_search;
    private RecyclerView article_recyclerView1,article_recyclerView2,article_recyclerView3;
    private Context context;
    private ArticleListBean bean;
    private String consumerId;
    /**
     * 下拉刷新
     */
    private RefreshLayout mRefreshLayout;
    private static boolean isFirstEnter = true;
    private View loadView;//loding页面（加载页）

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ApplicationUtils applicationUtils = new ApplicationUtils();
        applicationUtils.addActivity(this);
        initView();
        ParsingData();
    }

    private void recyclerViewAdapter() {
        FullyLinearLayoutManager linearLayoutManager = new FullyLinearLayoutManager(this);
        FullyLinearLayoutManager linearLayoutManager2 = new FullyLinearLayoutManager(this);
        FullyLinearLayoutManager linearLayoutManager3 = new FullyLinearLayoutManager(this);
        linearLayoutManager.setScrollEnabled(false);
        linearLayoutManager2.setScrollEnabled(false);
        linearLayoutManager3.setScrollEnabled(false);
        article_recyclerView1.setLayoutManager(linearLayoutManager);
        article_recyclerView2.setLayoutManager(linearLayoutManager2);
        article_recyclerView3.setLayoutManager(linearLayoutManager3);
        article_recyclerView1.setHasFixedSize(true);
        article_recyclerView2.setHasFixedSize(true);
        article_recyclerView3.setHasFixedSize(true);
        ArticleRecyclerView1Adapter adapter1 = new ArticleRecyclerView1Adapter(context,bean.getArticle());
        ArticleRecyclerView2Adapter adapter2 = new ArticleRecyclerView2Adapter(context,bean.getArticle1());
        ArticleRecyclerView3Adapter adapter3 = new ArticleRecyclerView3Adapter(context,bean.getArticle2());
        article_recyclerView1.setAdapter(adapter1);
        article_recyclerView2.setAdapter(adapter2);
        article_recyclerView3.setAdapter(adapter3);
        adapter1.setOnItemClickListener(new ArticleRecyclerView1Adapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent();
                intent.putExtra("consumerId",consumerId);
                intent.putExtra("articleId",bean.getArticle().get(position).getArticleid());
                intent.setClass(ArticlePage.this, ArticleDetailsPage.class);
                startActivity(intent);
                overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
            }
        });
        adapter2.setOnItemClickListener(new ArticleRecyclerView2Adapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent();
                intent.putExtra("consumerId",consumerId);
                intent.putExtra("articleId",bean.getArticle1().get(position).getArticleid());
                intent.setClass(ArticlePage.this, ArticleDetailsPage.class);
                startActivity(intent);
                overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
            }
        });
        adapter3.setOnItemClickListener(new ArticleRecyclerView3Adapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent();
                intent.putExtra("consumerId",consumerId);
                intent.putExtra("articleId",bean.getArticle2().get(position).getArticleid());
                intent.setClass(ArticlePage.this, ArticleDetailsPage.class);
                startActivity(intent);
                overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
            }
        });
    }

    private void Listener() {
        article_title_bar_returns.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //底部加载
            }

            @Override
            public void onRefresh(final RefreshLayout refreshlayout) {
                //下拉刷新
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ParsingData();
                        refreshlayout.finishRefresh();
                    }
                }, 2000);
            }
        });
        article_title_bar_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ArticlePage.this,SearchPage.class);
                intent.putExtra("searchTid","3");
                startActivity(intent);
                overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
            }
        });
    }

    private void initView() {
        setContentView(R.layout.activity_article_page);
        Intent intent = getIntent();
        consumerId = intent.getStringExtra("consumerId");
        loadView = findViewById(R.id.loadView);
        banner = (Banner) findViewById(R.id.banner_two);
        article_title_bar_search = (ImageView) findViewById(R.id.article_title_bar_search);
        article_title_bar_returns = (ImageView) findViewById(R.id.article_title_bar_returns);
        article_recyclerView1 = (RecyclerView) findViewById(R.id.article_recyclerView1);
        article_recyclerView2 = (RecyclerView) findViewById(R.id.article_recyclerView2);
        article_recyclerView3 = (RecyclerView) findViewById(R.id.article_recyclerView3);
        /**
         * 下拉刷新
         */
        mRefreshLayout = (RefreshLayout)findViewById(R.id.refreshLayout);
        setThemeColor(R.color.colorPrimary);
        if (isFirstEnter) {
            ParsingData();
            isFirstEnter = false;
//            mRefreshLayout.autoRefresh();//第一次进入触发自动刷新，演示效果
        }
    }

    private void setThemeColor(int colorPrimary) {
        mRefreshLayout.setPrimaryColorsId(colorPrimary, android.R.color.holo_blue_dark);
        //改变手机状态栏背景色
//        if (Build.VERSION.SDK_INT >= 21) {
//            getActivity().getWindow().setStatusBarColor(ContextCompat.getColor(getActivity(), colorPrimaryDark));
//        }
    }

    public void ParsingData(){
        String url = AppUrl.URL+AppUrl.ArticleListsURL;
        XUtils.Post(url,null,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Gson gson = new Gson();
                bean = gson.fromJson(result,ArticleListBean.class);
                cateid = new String[bean.getBanner().size()];
                id = new String[bean.getBanner().size()];
                images=new ArrayList<>();
                titles = new ArrayList<>();
                if(bean.getBanner()!=null){
                    for (int i=0;i<bean.getBanner().size();i++){
                        //ViewPager数据源
                        String imageUrl = (bean.getBanner().get(i).getImgurl());
                        cateid[i] = bean.getBanner().get(i).getCateid();
                        id[i] = bean.getBanner().get(i).getId();
                        images.add(AppUrl.URL+imageUrl.substring(1,imageUrl.indexOf("|")));
                        titles.add(bean.getBanner().get(i).getBannerTitle());
                    }
                }
                recyclerViewAdapter();
                banner();
                loadView.setVisibility(View.GONE);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                LogUtil.e(ex.getMessage()+"联网请求失败");
            }
        });
        Listener();
    }

    /**
     * 顶部ViewPager样式设置
     */
    public void banner() {

        banner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                enableDisableSwipeRefresh(state == ViewPager.SCROLL_STATE_IDLE);
            }

        });
        //设置banner样式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE);
//        banner.setIndicatorGravity(BannerConfig.LEFT);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner.setImages(images);
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.Default);
        //设置标题集合（当banner样式有显示title时）
        banner.setBannerTitles(titles);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(4000);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        //banner设置方法全部调用完毕时最后调用
        banner.start();
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Intent intent = new Intent();
                switch (position){
                    case 0:
                        intent.putExtra("consumerId",consumerId);
                        intent.putExtra("articleId",id[0]);
                        intent.setClass(ArticlePage.this, ArticleDetailsPage.class);
                        startActivity(intent);
                        overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
                        break;
                    case 1:
                        intent.putExtra("consumerId",consumerId);
                        intent.putExtra("articleId",id[1]);
                        intent.setClass(ArticlePage.this, ArticleDetailsPage.class);
                        startActivity(intent);
                        overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
                        break;
                    case 2:
                        intent.putExtra("consumerId",consumerId);
                        intent.putExtra("articleId",id[2]);
                        intent.setClass(ArticlePage.this, ArticleDetailsPage.class);
                        startActivity(intent);
                        overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
                        break;
                }
            }
        });
    }

    protected void enableDisableSwipeRefresh(boolean enable) {
        if (mRefreshLayout != null) {
//            setEnabled(enable)
            mRefreshLayout.setEnableRefresh(enable);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束轮播
        banner.stopAutoPlay();
    }
}
